<?php

namespace app\pc\controller;
use app\base\controller\Base;
use think\Request;
use think\Cache;
use think\Config;
use think\Loader;

//用户询价处理
class Enquiry extends Base
{
    public  $model;

    public function __construct()
    {
        $this->model = model("UsersInquiry");
        $this->sharemodel = model("Shares");
        $this->UsersInquiryMain = model("UsersInquiryMain");
        parent::__construct();
        $this->Configs = controller('base/Configs', 'event');
        $rows = Cache::get($this->Cstatic->get("sid"));
        $this->sid_user_id = $rows['id'];
        $this->sid_mobile = $rows['mobile'];
    }

    /**
     * @param Request $request
     * @return \think\response\Json
     */
  public function save(Request $request)
    {
        $stock = $this->sharemodel->find(["id" => $this->stock_id]);
        if(empty($stock)){
            return   failJson($this->ecLang("failstock"));
        }
        $inser_id = $this->UsersInquiryMain->save(['user_id' => $this->sid_user_id]);
        if(empty($inser_id)){
            return   failJson($this->ecLang("failInsert"));
        }
        $inser_id = $this->UsersInquiryMain->getLastInsID();
        $mouth_config = get_m_config("q_time");
        $m_config = array_column($mouth_config, "id");
        //过滤月份
       $mouths = explode(",", $this->mouths);
       if(!empty($mouths)&&is_array($mouths)){
           $mouths = array_filter($mouths, function($val)use($m_config){
                            return in_array($val, $m_config);
                });
       }

        $ConfigsModel= new \app\admin\model\Configs();//用户
        $resConfig = $ConfigsModel->where("key","aotoprice")->where("group_config_id",0)->find();
       $data = [
           "stock_id"=>$this->stock_id, //股票代码id
           "capital_money"=>$this->capital_money, //名义本金
           "user_id"=>$this->sid_user_id,
           "main_id"=>$inser_id,
           "auto"=>$resConfig['value']?1:0,
           "ask_time"=>time(),
       ];
       $t_data  = array_map(function($v) use($data){
                 return  array_merge($data,['mouth_config_id'=>$v]);

       },$mouths);


        if($resConfig['value']){ //1 自动询价
            $resConfigMouth = $ConfigsModel->where("group_config_id",2)->select();
            $resConfigMouth = json_decode(json_encode($resConfigMouth),true);
            $Shares = model("Shares");
            $dk = $Shares->where("id",$this->stock_id)->find();
            if($resConfig['value']==1){//自动询价
                $result =  $this->model->saveAsk($t_data,$resConfigMouth);
                if($result['status']){
                    return   sucessJson($this->ecLang("scuessEnquire"),array_merge($result['data'],['auto'=>1]));
                }

                addMessage($this->sid_user_id,"尊敬的用户{$this->sid_mobile},股票".$dk->name."询价失败了");
                return   failJson($this->ecLang("failEnquire"));
            }else if($resConfig['value']==2){//上传依赖
                $result =  $this->model->saveAskUpload($t_data,$resConfigMouth);
                if($result['status']){
                    return   sucessJson($this->ecLang("scuessEnquire"),array_merge($result['data'],['auto'=>1]));
                }
                addMessage($this->sid_user_id,"尊敬的用户{$this->sid_mobile},股票".$dk->name."询价失败了");
                return   failJson($this->ecLang("failEnquire"));

            }

        }else{
            //手动询价
            $result = $this->model->saveAll($t_data);
            $Shares = model("Shares");
            $dk = $Shares->where("id",$this->stock_id)->find();
            if(empty($result)){
                //询价失败
                addMessage($this->sid_user_id,"尊敬的用户{$this->sid_mobile},股票".$dk->name."询价失败了");
                return   failJson($this->ecLang("failEnquire"));
            }
            //询价成功
            addMessage($this->sid_user_id,"尊敬的用户{$this->sid_mobile},股票".$dk->name."询价失败了");
            return   sucessJson($this->ecLang("scuessEnquire"),['auto'=>0]);
        }






    }


    //询价历史

    public function histroy(){
      //用户询价记录
        $res =$this->model->getHis($this->sid_user_id);
        $mouth_config = get_m_config("q_time");
        if(!empty($res['res'])&&is_array($res['res'])){

            return   sucessJson($this->ecLang("scuesshistroy"), $res);
        }
        return   failJson($this->ecLang("failhistroy"));

    }
    //询价成功的列表


    public function histroysucess(){
        //用户询价记录
        $res =$this->model->getHissucess($this->sid_user_id);
        if(!empty($res['res'])&&is_array($res['res'])){
            return   sucessJson($this->ecLang("scuesshistroy"), $res);
        }
        return   failJson($this->ecLang("failhistroy"));

    }



    //询价详情
    public function details(){
            $where['a.id'] = $this->id;
            $where['a.user_id'] = $this->sid_user_id;
            $res = $this->model->hisdetails($where);
        if(!$res){
            return   failJson($this->ecLang("detail_no"));
        }
        $res['mobile'] = $this->sid_mobile;
        return sucessJson($this->ecLang("detail_yes"), $res->toArray());

    }
    /**
     *  一鍵下單    //处理下单流程 進入委托中....
     */
    public function Oneclick(){

        $UsersMoney= new \app\np\model\UsersMoney; //用户
        //$this->sid_user_id
       $moneyList =  $UsersMoney->where("user_id", $this->sid_user_id)->find();
       if(empty($moneyList) || empty($moneyList->getData())){
           return   failJson($this->ecLang("moneyList"));
       }
               ;//已经确认询价的询价id
               $ids_ = explode(",", $this->ids);
               if(!empty($ids_)){
                   $ids_ = array_filter($ids_, function($val){
                       return is_numeric($val);
                   });
                   $len = count(array_filter($ids_));
                   if(!empty($ids_))
                   {
                       $where['a.id'] = ["in", $ids_ ];
                       $where['users_askprice.status'] =1;
                       $where['a.user_id'] = $this->sid_user_id;
                       //其他查詢條件
                   }
                   //
                   $res = $this->model->getDataOrder($where);

               }
               //参数检测
                if(isset($res))
                {
                   $count = count($res);
                    if($len!=$count){
                        return   failJson("你未验证？");
                    }
                }else{
                    return   failJson($this->ecLang("parmasfail"));

                }
                $total = array_sum(array_column($res->toArray() ,"manage_money"));
                //用户资金
                if($total>$moneyList['advisable']){
                    return   failJson("资金不足,暂时无法下单,请先完成其他订单");
                }

                //用户资金
                if($total>$moneyList['money']){
                    return   failJson($this->ecLang("no_money"));
                }
              //用户下单
              $mainOrderData = [
                  'status' => 1,
                  "user_id" => $this->sid_user_id,
                  "total" => $total
              ];
               $resData  = $this->model->delwithOrders($mainOrderData, $res);
               if($resData){
                   //下单成功
                   return   sucessJson($this->ecLang("scuesshistroy"));
               }

                return   failJson($this->ecLang("scuesshistroy"));

    }





}
